// routes/dingtalk.js
import express from "express";
import axios from "axios";
import {DINGTALK_APP_KEY, DINGTALK_APP_SECRET} from "../config/dingtalkConfig.js";

const router = express.Router();

// 获取 accessToken
async function getAccessToken() {
    const res = await axios.post("https://api.dingtalk.com/v1.0/oauth2/accessToken", {
        appKey: DINGTALK_APP_KEY,
        appSecret: DINGTALK_APP_SECRET
    });

    return res.data.accessToken;
}


// ===================== 钉钉登录验证接口 =====================
router.get('/getUserInfo', async (req, res) => {
    try {
        const {code} = req.query
        console.log("code:", code)
        const token = await getAccessToken()
        const resp = await fetch(`https://oapi.dingtalk.com/topapi/v2/user/getuserinfo?access_token=${token}`, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({code})
        })
        const userData = await resp.json()
        const user = userData.result
        const isInternal = user.corp_id === DING_CORP_ID
        res.json({
            success: true,
            userId: user.userid,
            name: user.name,
            isInternal
        })
    } catch (err) {
        res.status(500).json({success: false, message: err.message})
    }
})


// ===================== 钉钉登录验证接口 =====================
router.post('/login', async (req, res) => {
    try {
        const {code} = req.body
        const accessToken = await getAccessToken()

        const userInfoRes = await axios.post(
            `https://oapi.dingtalk.com/topapi/v2/user/getuserinfo?access_token=${accessToken}`,
            {code},
            {headers: {'Content-Type': 'application/json'}}
        )

        const data = userInfoRes.data
        if (data.errcode === 0) {
            // 企业内部员工
            res.json({
                success: true,
                userid: data.result.userid,
                name: data.result.name
            })
        } else {
            // 非企业内部员工或错误
            res.json({
                success: false,
                message: data.errmsg || '非企业内部员工'
            })
        }
    } catch (err) {
        console.error(err)
        res.status(500).json({success: false, message: '钉钉验证失败', error: err.message})
    }
})

export default router;
